from flask import Flask, render_template, request, escape
import geo
import pandas as pd

key ="a9758bee89912716bcdb624bc0338c84"
app = Flask(__name__)

def direction(key, start_address, end_address):
    """    """
    start = geo.geocode(key, start_address)['geocodes'][0]['location']
    end = geo.geocode(key, end_address)['geocodes'][0]['location']
    results = geo.walk(key, start, end)
    df = pd.json_normalize(results['route']['paths'][0]['steps'])
    return df


def total_distance(df):
    """    """
    distance = df['distance'].to_list()
    sum_num = 0
    for i in distance:
        sum_num += int(i)
    return sum_num


def total_time(df):
    """    """
    duration = df['duration'].to_list()
    sum_num = 0
    for i in duration:
        sum_num += int(i)
    return sum_num // 60

def log_request(req: 'flask_request', res: str) -> None:
    """ """
    with open('walking.log','a') as log:
        print(req.form, req.remote_addr, req.user_agent, res, file=log, sep='|')

@app.route('/')
def entry():
    title = '欢迎来看看怎么走到你的目的地:)'
    return render_template('entry.html',
                            the_title=title,
                            )

@app.route('/results',methods=['POST'])
def result_page() -> 'html':
    key = request.form['key']
    start_address = request.form['start']
    end_address = request.form['end']
    title = '这样走'
    df = direction(key, start_address, end_address)
    results = df.loc[:, ['instruction', 'distance', 'duration']]
    results.columns = ['指引', '路程', '时间']
    the_distance = total_distance(df)
    the_time = total_time(df)
    route = results['指引'].tolist()
    log_request(request, route)
    return render_template('results.html',
                           the_title=title,
                           the_start_address=start_address,
                           the_end_address=end_address,
                           the_results=results,
                           the_html_table=results.to_html(index=False),
                           the_total_walk=the_distance,
                           the_total_walk_time=the_time, )

@app.route('/viewlog')
def view_log() -> 'html':
    contents=[]
    with open('geoapi.log','r') as log:
        for line in log:
            contents.append([])
            for item in line.split("|"):
                contents[-1].append(escape(item))
    titles = ('用户输入数据','远程机器的IP地址','用户代理','查询结果')
    return render_template('viewlog.html',
                           the_title='日志系统',
                           row_titles=titles,
                           the_data=contents,
                           )

if __name__ == '__main__':
    app.run(debug=True)
